package com.zywl.web.controller.sys;

import com.zywl.core.beans.User;
import com.zywl.service.ResourceService;
import com.zywl.service.UserService;
import com.zywl.utils.utils.Constants;
import com.zywl.utils.utils.IPUtil;
import com.zywl.utils.utils.enums.ResTypeEnum;
import com.zywl.web.controller.base.BaseController;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/")
public class IndexController extends BaseController {
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private UserService userService;

    @GetMapping("/index")
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("index");
        User user = (User) request.getSession().getAttribute(Constants.USER_SESSION_KEY);
        if (user != null) {
            try {
                user = userService.getById(user.getUsrId());
                if (user != null) {
                    String headPic = user.getUsrAvatar();
                    if (StringUtils.isNotEmpty(headPic)) {
                        user.setUsrAvatar(IPUtil.getIpPath(request) + headPic + "?t=" + System.currentTimeMillis());
                    }
                    mav.addObject("user", user);
                    request.getSession().setAttribute("username",user.getUsrName());//添加用户名

                }
                if ("admin".equals(user.getUsrUsername()) || user.getUsrAssociationId() == null){
                    mav.addObject("permissions", resourceService.getResources(ResTypeEnum.MENU.getKey()));
                }else{
                    if(user.getUsrRoleId() == null){
                        mav.addObject("permissions", resourceService.getAllByAssIdAndType(user.getUsrAssociationId(), ResTypeEnum.MENU.getKey()));
                    }else{
                        mav.addObject("permissions", resourceService.getResourcesByRoleId(user.getUsrRoleId(), ResTypeEnum.MENU.getKey()));
                    }
                }
            } catch (Exception e) {
                logger.error("获取绑定数据异常", e);
            }
        }
        return mav;
    }
}
